<?php
/**
 *
 * @author nhan
 *
 */
class Dao_UserDAO extends Dao_AbstractDAO {

	public function __construct($db = null) {
		parent::__construct($db);
		$this->tableName = "users";
		$this->key = "id";
		$this->classModel = "Model_User";
	}

	/**
	 *
	 * @param string $username
	 * @param string $password
	 * @return Model_User
	 */
	public function login($username, $password) {
		$passnew = Controller_LoginController::createPassword($username, $password);
		$query = $this->createSQLLogin( $passnew);
		$user = $this->getOneObject($query);
		return $user;
	}

	private function createSQLLogin($passnew) {
		$query = " SELECT * FROM $this->tableName T ";
		$query .= " WHERE T.password = '".$passnew."' ";
		return $query;
	}

	public function insertProduct(Model_Product $product){
		if ($product === null) {
			return false;
		}

		$this->startTransaction();
		$success = $this->insertModel($product);

		if ($success) {
			$this->commitTransaction();
			return true;
		} else {
			$this->rollBackTransaction();
			return false;
		}

		return $success;
	}

	public function updateProduct(Model_Product $product){
		if ($product === null) {
			return false;
		}
		$success = false;

		$sql = $this->startTransaction();

		$success = $this->updateModelById($product);

		if ($success) {
			$this->commitTransaction();
		} else {
			$this->rollBackTransaction();
		}

		return $success;
	}

	public function insertOrUpdate(Model_Product $product) {
		$success = false;
		if ($product->getId() !== null) {

			$success = $this->updateProduct($product);
		} else {
			$success = $this->insertProduct($product);
		}
		return $success;
	}

}